/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.news.server.check.checkers;

import cn.ac.iie.di.ban.news.server.check.CheckResult;
import cn.ac.iie.di.ban.news.server.check.Checker;
import cn.ac.iie.di.ban.news.server.util.MD5Pool;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedList;
import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 *
 * @author zwlin
 */
public class MD5Checker implements Checker<String, String> {

	MD5Pool pool;

	public MD5Checker() {
		pool = MD5Pool.getInstance();
	}

	@Override
	public CheckResult check(String src, String target) {
		LinkedList<Character> list = new LinkedList<>();
		for (char c : target.toCharArray()) {
			list.add(c);
		}
		try {
			MessageDigest md = pool.Borrow();
			try {
				byte[] bs = md.digest(src.getBytes());
				int i;
				StringBuilder sb = new StringBuilder();
				for (byte b : bs) {
					i = b & 0xffff;
					if (i < 16) {
						sb.append('0');
					}
					sb.append(Integer.toHexString(i));
				}
				for (char a : sb.toString().toCharArray()) {
					if (a != list.pop()) {
						return new CheckResult("MD5 of content error.");
					}
				}
				return new CheckResult();
			} finally {
				if (md == null) {
					pool.Return(md);
				}
			}
		} catch (NoSuchAlgorithmException ex) {
			return new CheckResult("MD5 checker error. " + ExceptionUtils.getStackTrace(ex));
		}
	}

}
